package ui.result;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;

public class QueryResultDialog extends JDialog {
    private final JTable table;
    private final JButton exportButton;
    private final JLabel statusLabel;

    public QueryResultDialog(JFrame parent, String[][] data, String[] columns) {
        super(parent, "查询结果", true);
        setSize(800, 600);
        setLocationRelativeTo(parent);

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel(data, columns);
        table = new JTable(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);

        // 创建工具栏
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);

        exportButton = new JButton("导出数据");
        exportButton.addActionListener(this::exportData);
        toolBar.add(exportButton);

        // 创建状态栏
        statusLabel = new JLabel("共 " + data.length + " 行数据");
        statusLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));

        // 布局
        setLayout(new BorderLayout());
        add(toolBar, BorderLayout.NORTH);
        add(new JScrollPane(table), BorderLayout.CENTER);
        add(statusLabel, BorderLayout.SOUTH);
    }

    private void exportData(ActionEvent e) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("导出查询结果");
        fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("CSV 文件", "csv"));

        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                String fileName = fileChooser.getSelectedFile().getAbsolutePath();
                if (!fileName.toLowerCase().endsWith(".csv")) {
                    fileName += ".csv";
                }

                // 实现导出逻辑
                exportToCSV(fileName);
                JOptionPane.showMessageDialog(this, "数据导出成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "导出失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void exportToCSV(String fileName) {
        // 实现CSV导出逻辑
        // 这里应该添加实际的CSV导出代码
    }

    public static void show(String[][] data, String[] columns) {
        JFrame parent = (JFrame) SwingUtilities.getWindowAncestor(null);
        QueryResultDialog dialog = new QueryResultDialog(parent, data, columns);
        dialog.setVisible(true);
    }
}

